#!/bin/bash
#pMusic - external menu
#GPL - Copyright Sigmund Berglund

[ $PTR_BTN != 3 ] && exit
export TEXTDOMAIN=pmusic
export OUTPUT_CHARSET=UTF-8
SF='space-expand="false" space-fill="false"'
ST='space-expand="true" space-fill="true"'

#simple frontends doesn't require/want this menu
[[ "$PMUSIC_FRONTEND" = @("$APPDIR"/frontends/.Podcast|"$APPDIR"/frontends/.Radio) ]] && exit


template_simple(){
	TMP="$*"
	[[ "$*" = *single-selection* && "$SOURCE" = *$'\n'* ]] && SENSITIVE='<sensitive>false</sensitive>'
	[[ "$*" = *tooltip* ]] && TOOLTIP="tooltip-text=\"${TMP#*tooltip=}\""
	echo '
	  <button xalign="0" relief="2" '$TOOLTIP' '$ST'>
	   '$SENSITIVE'
	   <label>'$1'</label>
	 <action signal="button-release-event">EXIT:'$2'</action>
	  </button>
	'
}

template(){
	TMP="$*"
	[[ "$*" = *single-selection* && "$SOURCE" = *$'\n'* ]] && SENSITIVE='<sensitive>false</sensitive>'
	[[ "$*" = *tooltip* ]] && TOOLTIP="tooltip-text=\"${TMP#*tooltip=}\""
	echo '
	<eventbox above-child="true" visible-window="true">
	 <hbox spacing="7" border-width="3">
	  <pixmap '$SF'><height>18</height><input file>'$APPDIR'/themes/'$THEME'/'$3'</input></pixmap>
	  <text xalign="0" '$TOOLTIP' '$ST'>
	   '$SENSITIVE'
	   <label>'$1'</label>
	  </text>
	 </hbox>
	 <action signal="enter-notify-event">hide:'$2'</action>
	 <action signal="enter-notify-event">show:'$2'B</action>
	 <variable>'$2'</variable>
	</eventbox>
	<eventbox name="rightclick_menu" above-child="true" visible-window="true" visible="false">
	 <hbox spacing="7" border-width="3">
	  <pixmap '$SF'><height>18</height><input file>'$APPDIR'/themes/'$THEME'/'$3'</input></pixmap>
	  <text xalign="0" '$TOOLTIP' '$ST'>
	   '$SENSITIVE'
	   <label>'$1'</label>
	  </text>
	 </hbox>
	 <action signal="leave-notify-event">show:'$2'</action>
	 <action signal="leave-notify-event">hide:'$2'B</action>
	 <action signal="button-release-event">EXIT:'$2'</action>
	 <variable>'$2'B</variable>
	</eventbox>
	'
}

add(){
	[ ! -s $WORKDIR/SOURCE_PRESS_EVENT ] && exit
	echo -n > $WORKDIR/tmp.add
	while read I; do
		case $I in 
			*http://*|*:+[0-9]*) #+[0-9] is jamendo items
				TMP="`cut -d'|' -f3 <<< $I`"
				$APPDIR/func_add -add "$TMP"
				;;
			[0-9]*)
				echo "||${I#*:}" >> $WORKDIR/tmp.add #remove unique source-nr
				;;
			*)
				if [ -d "$I" ]; then #add all songs in directory 
					gettext 'Importing tracks from directory' > $WORKDIR/splashtext
					$APPDIR/box_splash &
					[ $EXIT = add_tail ] && DEPTH="1" || DEPTH="99"
					find "$I" -maxdepth "$DEPTH" -printf "||%p\n" | grep -iE "$AUDIO_FORMATS" | sort >> $WORKDIR/tmp.add
					echo 100 > $WORKDIR/splash
				elif [[ ${I} = /* ]]; then
					echo "||${I}" >> $WORKDIR/tmp.add #browsing files
				else
					$APPDIR/func_add -add "${I#*:}" #add playlists one by one
				fi
				;;
		esac
	done < $WORKDIR/SOURCE_PRESS_EVENT
	[ -s $WORKDIR/tmp.add ] && $APPDIR/func_add -add $WORKDIR/tmp.add
}
export add template

read PRESS_EVENT < $WORKDIR/SOURCE_PRESS_EVENT
#SOURCE=${PRESS_EVENT#[0-9]*:}; SOURCE=${SOURCE//pmusicbrowse_*:/}
[[ "$SOURCE" = @([0-9]*|pmusic*) ]] && SOURCE="`cut -d: -f2- <<< "$SOURCE"`" #cut (not bash) is required for multiple selection 
[[ "$SOURCE" = *"http"* && "$(<"$STORAGE_DIR"/index_radio)" = *"$SOURCE"* ]] && RADIO_STREAM=true

#---
echo -n > $WORKDIR/tmp_favorite_list
#are we in favorites?
if [ "`grep -FB 10000 -m1 'pmusic_rating' $WORKDIR/sourcelist | grep -vF 'pmusic_rating' | grep -FA 10000 'pmusic_favorites' | grep -F "$SOURCE"`" ]; then
	#what favorite list are we working in ?
	if [ "`tac $WORKDIR/sourcelist | grep -FA 10000 'pmusic_expand_end' | tac | grep -Fm1 "$SOURCE"`" ] && [ "`grep -iE "$AUDIO_FORMATS|^http|^cdda:" $WORKDIR/SOURCE_PRESS_EVENT`" ] && [ "`grep -Fm1 -B 1000 "$SOURCE" $WORKDIR/sourcelist | grep -Fm1 '.pmd|'`" ]; then
		F="`grep -Fm1 -B 1000 "$SOURCE" $WORKDIR/sourcelist | tac | grep -Fm1 '.pmd|'`"
		F=${F%%|*}; export FAV_LIST=${F#pmusicbrowse_*:}
	fi
	export FAV=true
fi

if [ "`grep -iE "$AUDIO_FORMATS|http|cdda:|^+[0-9]:/" $WORKDIR/SOURCE_PRESS_EVENT`" ]; then #only tracks can be placed inside a favorite list
	MENUITEMS='
	<menuitem><label>"'$(gettext 'No list - add as mark')'"</label><action>clear:FAVORITE_LIST</action></menuitem>
	<menuitemseparator></menuitemseparator>'"
	`find "$STORAGE_DIR/favorite_lists/" -type f -printf "<menuitem><label>\\\"%f\\\"</label><action>echo \\\"%f\\\" > $WORKDIR/tmp_favorite_list</action><action>refresh:FAVORITE_LIST</action></menuitem>\n" | sed 's%.pmd%%g' | sort`"
	 
	gettext 'My favorite list' > $WORKDIR/tmp_favorite_list #default value
	S=$S'
	<eventbox above-child="true" visible-window="true">
	 <hbox spacing="7" border-width="3">
	  <pixmap '$SF'><height>18</height><input file>'$APPDIR'/themes/'$THEME'/icon_favorites_add.svg</input></pixmap>
	  <text xalign="0" '$ST'>
	   <label>'$(gettext 'Add to Favorites')'</label>
	  </text>
	 </hbox>
	 <action signal="enter-notify-event">hide:FAV_ADD</action>
	 <action signal="enter-notify-event">show:FAV_ADDB</action>
	 <variable>FAV_ADD</variable>
	</eventbox>
	<eventbox name="rightclick_menu" above-child="true" visible-window="true" visible="false">
	 <hbox spacing="7" border-width="3">
	  <pixmap '$SF'><height>18</height><input file>'$APPDIR'/themes/'$THEME'/icon_favorites_add.svg</input></pixmap>
	  <text xalign="0" '$ST'>
	   <label>'$(gettext 'Add to Favorites')'</label>
	  </text>
	 </hbox>
	 <action signal="leave-notify-event">show:FAV_ADD</action>
	 <action signal="leave-notify-event">hide:FAV_ADDB</action>
	 <action signal="button-release-event">show:HBOX_FAV</action>
	 <variable>FAV_ADDB</variable>
	</eventbox>
	
	<hbox visible="false" spacing="2" tooltip-text="'$(gettext 'What favorite list should the item be added to?
An empty field adds a favorite Mark')'">
	 <text width-request="25"><label>""</label></text>
	 <entry secondary-icon-stock="gtk-clear">
	  <variable>FAVORITE_LIST</variable>
	  <input file>'$WORKDIR'/tmp_favorite_list</input>
	  <output file>'$WORKDIR'/tmp_favorite_list</output>
	  <action signal="secondary-icon-release">clear:FAVORITE_LIST</action>
	  <action signal="activate">save:FAVORITE_LIST</action>
	  <action signal="activate">EXIT:add_favorites</action>
	 </entry>
	 <menubar>
	  <menu>
	  '"$MENUITEMS"'
	  <label>..</label>
	  </menu>
	 </menubar>
	 <button stock-icon-size="1">
	  <input file stock="gtk-favorites_add"></input>
	  <height>16</height>
	  <action>save:FAVORITE_LIST</action>
	  <action>EXIT:add_favorites</action>
	 </button>
	 <variable>HBOX_FAV</variable>
	</hbox>'
elif [[ "$PRESS_EVENT" != *"$STORAGE_DIR/favorite_lists/"* ]] && [ -d "$SOURCE" -o "`grep -iE "\.pmu$|\.m3u$|\.pls$" $WORKDIR/SOURCE_PRESS_EVENT`" ]; then
	S=$S"
	$(template " $(gettext 'Add to Favorites')" add_favorites icon_favorites_add.svg)"
fi
if [ "$FAV" = "true" ]; then
	case $SOURCE in *.pmd)
		MENUITEMS="`find "$STORAGE_DIR/favorite_lists/" -mindepth 1 -type d -printf "<menuitem><label>\\\"%f\\\"</label><action>echo \\\"%f\\\" > $WORKDIR/tmp_favorite_group</action><action>refresh:FAVORITE_GROUP</action></menuitem>\n"`"
		[ ! "$MENUITEMS" ] && MENUITEMS="<menuitem><label>".."</label></menuitem>"
		gettext 'My favorite group' > $WORKDIR/tmp_favorite_group #default value
		S=$S'
		<eventbox above-child="true" visible-window="true">
		 <hbox spacing="7" border-width="3">
		  <pixmap '$SF'><height>18</height><input file>'$APPDIR'/themes/'$THEME'/icon_favorites_add.svg</input></pixmap>
		  <text xalign="0" '$ST'>
		   <label>'$(gettext 'Move favorite list to group')'</label>
		  </text>
		 </hbox>
		 <action signal="enter-notify-event">hide:FAV_MOVE</action>
		 <action signal="enter-notify-event">show:FAV_MOVEB</action>
		 <variable>FAV_MOVE</variable>
		</eventbox>
		<eventbox name="rightclick_menu" above-child="true" visible-window="true" visible="false">
		 <hbox spacing="7" border-width="3">
		  <pixmap '$SF'><height>18</height><input file>'$APPDIR'/themes/'$THEME'/icon_favorites_add.svg</input></pixmap>
		  <text xalign="0" '$ST'>
		   <label>'$(gettext 'Move favorite list to group')'</label>
		  </text>
		 </hbox>
		 <action signal="leave-notify-event">show:FAV_MOVE</action>
		 <action signal="leave-notify-event">hide:FAV_MOVEB</action>
		 <action signal="button-release-event">show:HBOX_FAV_GROUP</action>
		 <variable>FAV_MOVEB</variable>
		</eventbox>	
	
		<hbox visible="false" spacing="2">
		 <text width-request="25"><label>""</label></text>
		 <entry secondary-icon-stock="gtk-clear" secondary-icon-tooltip-text="'$(gettext 'Remove text in field')'">
		  <variable>FAVORITE_GROUP</variable>
		  <input file>'$WORKDIR'/tmp_favorite_group</input>
		  <output file>'$WORKDIR'/tmp_favorite_group</output>
		  <action signal="secondary-icon-release">clear:FAVORITE_GROUP</action>
		  <action signal="activate">save:FAVORITE_GROUP</action>
		  <action signal="activate">EXIT:group_favorites</action>
		 </entry>
		 <menubar>
		  <menu>
		  '"$MENUITEMS"'
		  <label>..</label>
		  </menu>
		 </menubar>
		 <button stock-icon-size="1">
		  <input file stock="gtk-favorites_add"></input>
		  <height>16</height>
		  <action>save:FAVORITE_GROUP</action>
		  <action>EXIT:group_favorites</action>
		 </button>
		 <variable>HBOX_FAV_GROUP</variable>
		</hbox>'

		S=$S"
		$(template " $(gettext 'Expand Favorite list')" expand icon_audio_playlist_favorites.svg)"
		;;
	esac
	if [[ "$PRESS_EVENT" = *"$STORAGE_DIR/favorite_lists/"* ]] && [[ ! "$PRESS_EVENT" = *.pmd ]]; then S=$S"
		$(template " $(gettext 'Ungroup')" favorites_ungroup icon_favorites_ungroup.svg)"
	fi
	if [[ "$SOURCE" != @(pmusic_favorite*|pmusic_rating*) ]]; then S=$S"
		$(template " $(gettext 'Remove from Favorites')" favorites_remove icon_favorites_remove.svg)
		$(template " $(gettext 'Edit Marks')" edit_marks icon_edit.svg)
		<hseparator height-request=\"5\"></hseparator>"
	fi
fi

###    A D D

if [ "$RADIO_STREAM" = "true" ]; then S=$S"
		$(template " $(gettext 'Play')" add_tail icon_play.svg)"
else
	if [ -d "$SOURCE" ] || [ "`grep -iE "$AUDIO_FORMATS|\.pmd$|\.pmu$|\.m3u$|\.pls$|http|cdda:|^+[0-9]:/" $WORKDIR/SOURCE_PRESS_EVENT`" ]; then S=$S"
		$(template " $(gettext 'Add to play queue')" add_tail icon_add_playqueue.svg)
		$(template " $(gettext 'Add as next playing track(s)')" add_next icon_add_next.svg)
		$(template " $(gettext 'Play track (middle-button)')" play icon_play.svg single-selection)"
		SEPARATOR=true
	fi
	if [ -d "$SOURCE" ]; then S=$S"
		$(template " $(gettext 'Add recursively to play queue')" add_tail_recursively icon_add_playqueue.svg)
		$(template " $(gettext 'Add recursively as next track(s)')" add_next_recursively icon_add_next.svg)"
		SEPARATOR=true
	fi

	###    T R A C K S   I N   P L A Y L I S T   /   A L B U M 

	#are we inside an expanded playlist
	case $PRESS_EVENT in *.pmu|*.m3u|*.pls) echo;; *)
		TMP="`grep -Fm1 -B 1000 "$PRESS_EVENT" $WORKDIR/sourcelist | tac`"
		if [ "`grep -iE -m1 "\.m3u\||\.pmu\||\.pls\||pmusic_expand_end" <<< "$TMP" | grep -F 'pmusicbrowse_collapse'`" ]; then S=$S"
			$(template " $(gettext 'Remove track from album / list')" remove_track_from_playlist icon_remove.svg)"
			SEPARATOR=true
		fi
		#are we inside an expanded pmu / playlist in general
		if [ "`grep -iE -m1 "\.pmu\||pmusic_expand_end" <<< "$TMP" | grep -F 'pmusicbrowse_collapse'`" ]; then S=$S"
			$(template " $(gettext '(Re)set source of track')" reset_source icon_refresh.svg single-selection)
			$(template " $(gettext 'Search for track')" search_track icon_pmusic_find.svg single-selection)"
			SEPARATOR=true
		fi
		;;
	esac
	[ "$SEPARATOR" = "true" ] && S=$S'<hseparator height-request="5"></hseparator>'

	###    P L A Y L I S T   T O O L S

	case $PRESS_EVENT in *.pmu|*.pmd|*.m3u|*.pls)
		case $PRESS_EVENT in *.pmu|*.m3u|*.pls)
			S=$S"$(template " $(gettext 'Expand album / list')" expand icon_audio_playlist.svg)"
			;;
		esac
		S=$S"$(template " $(gettext 'Open in text editor')" edit_text icon_edit.svg)"
		case $PRESS_EVENT in *.pmu)
			S=$S"$(template " $(gettext 'Research non-existing tracks')" fix_album icon_audio_playlist_setup.svg single-selection tooltip="$(gettext 'This will not touch already defined tracks in list')")"
			;;
		esac
		case $PRESS_EVENT in *$STORAGE_DIR/pmu/*)
			S=$S"$(template " $(gettext 'Rebuild complete album')" rebuild_album icon_audio_playlist_setup.svg single-selection tooltip="$(gettext 'This will delete list and build a new based on internet information')")"
			;;
		esac
		S=$S"<hseparator height-request=\"5\"></hseparator>"
		;;
	esac

	###   T R A C K

	if [ "`grep -iE "$AUDIO_FORMATS|http|^+[0-9]:/" $WORKDIR/SOURCE_PRESS_EVENT`" ]; then
		S=$S"
		$(template " $(gettext 'Track info')" track_info icon_info.svg single-selection)"
		if [ "`grep -iE "$AUDIO_FORMATS" $WORKDIR/SOURCE_PRESS_EVENT`" ]; then
			S=$S"
			$(template " $(gettext 'Send to export')" send_to_export icon_pmusic_redo.svg)
			$(template " $(gettext 'Send to masstagger')" masstagger icon_pmusic_redo.svg)
			<hseparator height-request=\"5\"></hseparator>
			"
		fi
	fi

	###   P O D C A S T
	if [[ "$PRESS_EVENT" = pmusicbrowse_podcast:* ]]; then
		if [ ! "`grep "$PRESS_EVENT" "$STORAGE_DIR"/podcast_channels`" ]; then #if not already in My podcasts, give option to add it
			S=$S"
			$(template " $(gettext 'Add channel to My Podcasts')" move_pod icon_move.svg single-selection)
			"
		fi
	fi

	###   F I L E
	if [[ ! "`grep -v "^/" <<< "$SOURCE"`" && "$SOURCE" ]]; then
		S=$S"
		$(template " $(gettext 'Copy source file')" copy icon_copy.svg)
		$(template " $(gettext 'Delete source file')" delete icon_delete.svg)
		"
	fi
	if [ -s "$SOURCE" ]; then
		S=$S"
		$(template " $(gettext 'Show location')" show_location icon_directory.svg single-selection)
		$(template " $(gettext 'Rename source file/directory')" rename icon_rename.svg single-selection)
		"
	elif [[ -f "$SOURCE" && "$SOURCE" != *$'\n'* ]]; then
		S=$S"
		$(template " $(gettext 'Fix corrupted file in database')" fix_db icon_audio.svg single-selection)
		"
	fi
	if [[ "`grep -F "$SOURCE" "$STORAGE_DIR/index_mymusic"`" && "$SOURCE" ]]; then
		S=$S"
		<hseparator height-request=\"5\"></hseparator>
		$(template " $(gettext 'Edit database entry')" edit_db icon_edit.svg)"
	fi
fi

[[ "$S" != *'<label>'* ]] && exit
export gtkdialog_menu='
<window decorated="false" skip_taskbar_hint="true" resizable="false" border-width="0" '$ST'>
 <eventbox name="rightclick_menu_frame" above-child="false">
  <vbox border-width="1">
   <eventbox>
    <vbox spacing="0" border-width="7">
     '$S'
    </vbox>
   </eventbox>
  </vbox>
 </eventbox>
 <action signal="focus-out-event">EXIT:exit</action>
</window>'

I=$IFS; IFS=""
for STATEMENTS in $($GTKDIALOG -p gtkdialog_menu -G +"$(($PTR_X_ROOT-5))"+"$(($PTR_Y_ROOT-5))"); do
	eval $STATEMENTS
done
IFS=$I

#remove internal commands for favorite groups (actually nothing else than a ordinary directory)
sed -i 's/pmusicbrowse_parent:pmusicbrowse_favorites://g' $WORKDIR/SOURCE_PRESS_EVENT

export PTR_BTN=""
[ $UTF8 != true ] && export LC_ALL=${LANG%%_*}

case $EXIT in

play)
	$APPDIR/func -play_direct "$SOURCE"
	;;

add_tail*)
	add
	;;

add_next*)
	echo next > $WORKDIR/ADDMODE
	add
	;;

expand)
	while read SOURCE; do
		$APPDIR/func -browse
		echo true > $WORKDIR/UPDATE_SOURCELIST
	done < $WORKDIR/SOURCE_PRESS_EVENT
	;;

remove_track_from_playlist)
	while read I; do
		ACTIVE_PLAYLIST="`grep -Fm 1 -B 1000 "$I" $WORKDIR/sourcelist | tac | grep -iE -m1 "\.m3u\||\.pmu\||\.pls\|" | grep -F 'pmusicbrowse_collapse' | cut -d'|' -f14`"
		ACTIVE_TRACK=${I#*:}
		[ ! "$ACTIVE_TRACK" ] && ACTIVE_TRACK="`grep -F "$I" $WORKDIR/sourcelist | cut -d'|' -f2 | cut -c5-`" #if dead item in pmu file
		#For albums (found by pMusic), we want to keep the track-name. Else album list is not complete.
		case $ACTIVE_PLAYLIST in
			*$STORAGE_DIR/pmu/*)
				case $ACTIVE_TRACK in /)
					ACTIVE_TRACK_NAME="`basename "$ACTIVE_TRACK" | sed -e 's/\.[^\.]*$//'`"
					TMP="`grep "|${ACTIVE_TRACK}|" "$ACTIVE_PLAYLIST"`"
					sed -i "s%${TMP}%||${ACTIVE_TRACK_NAME}||||||||||%" "$ACTIVE_PLAYLIST"
					;;
				esac
				;;
			*.pls)
				NR="`grep "${ACTIVE_TRACK}$" "$ACTIVE_PLAYLIST" | cut -d= -f1 | cut -d'e' -f2`"
				grep -v "^File${NR}=" "$ACTIVE_PLAYLIST" | grep -v "^Title${NR}=" | grep -v "^Length${NR}=" > $WORKDIR/tmp_pls
				#build new playlist
				COUNT=0
				echo -n -e "[playlist]\nNumberOfEntries=" > $WORKDIR/tmp2_pls
				grep -c "^File" $WORKDIR/tmp_pls >> $WORKDIR/tmp2_pls
				while read I; do
					case $I in
						File*)		COUNT=$(($COUNT+1))
									echo File${COUNT}=${I#*=} >> $WORKDIR/tmp2_pls;;
						Title*)		echo Title${COUNT}=${I#*=} >> $WORKDIR/tmp2_pls;;
						Length*)	echo Length${COUNT}=${I#*=} >> $WORKDIR/tmp2_pls;;
					esac
				done < $WORKDIR/tmp_pls
				mv $WORKDIR/tmp2_pls "$ACTIVE_PLAYLIST"
				;;
			*.m3u)
				grep -v "^${ACTIVE_TRACK}$" "$ACTIVE_PLAYLIST" > $WORKDIR/tmp_sourcelist
				mv $WORKDIR/tmp_sourcelist "$ACTIVE_PLAYLIST"
				;;
			*.pmu)
				grep -v "|${ACTIVE_TRACK}|" "$ACTIVE_PLAYLIST" > $WORKDIR/tmp_sourcelist
				mv $WORKDIR/tmp_sourcelist "$ACTIVE_PLAYLIST"
				;;
		esac
	done < $WORKDIR/SOURCE_PRESS_EVENT
	$APPDIR/func -playlist_collapse "$ACTIVE_PLAYLIST"
	$APPDIR/func -playlist_expand "$ACTIVE_PLAYLIST"
	echo true > $WORKDIR/UPDATE_SOURCELIST
	;;

reset_source) #only inside pmu files
	IFS='|' read COMMAND ARTIST TITLE TMP <<< "$(grep -Fm1 "$(<$WORKDIR/SOURCE_PRESS_EVENT)|" $WORKDIR/sourcelist)"
	[ "$TITLE" ] && TMP="$ARTIST - $TITLE" || TMP="$ARTIST"
	$APPDIR/box_open track $HOME "$TMP" #$1=mode $2=default_dir $3=window_title
	read < $WORKDIR/open_output
	if [ "$REPLY" ]; then
		ACTIVE_PLAYLIST="`grep -Fm1 -B 1000 "$PRESS_EVENT" $WORKDIR/sourcelist | tac | grep -Fm1 'pmusicbrowse_collapse' | cut -d'|' -f14`"
		ACTIVE_TRACK="${PRESS_EVENT#*:}"
		[ ! "$ACTIVE_TRACK" ] && ACTIVE_TRACK="`grep -Fm1 "$PRESS_EVENT" $WORKDIR/sourcelist | cut -d'|' -f2 | cut -c 5-`" #if dead item in pmu file
		#now, let's replace
		grep -FB1000 "|${ACTIVE_TRACK}|" "$ACTIVE_PLAYLIST" | grep -vF "|${ACTIVE_TRACK}|" > $WORKDIR/tmp_sourcelist
		IFS='|' read ADR ARTIST TITLE ALBUM NR YEAR GENRE COMMENT RATING FORMAT BITRATE LENGTH TMP <<< "$(grep -Fm1 "${REPLY}|" "$STORAGE_DIR/index_mymusic")"
		INFO="$ARTIST - $TITLE"
		[ "$INFO" = ' - ' ] && INFO="${REPLY##*/}"
		echo "|$LENGTH|$INFO|$REPLY|`date +%s%N` $REPLY" >> $WORKDIR/tmp_sourcelist
		grep -FA1000 "|${ACTIVE_TRACK}|" "$ACTIVE_PLAYLIST" | grep -vF "|${ACTIVE_TRACK}|" >> $WORKDIR/tmp_sourcelist
		mv -f  $WORKDIR/tmp_sourcelist "$ACTIVE_PLAYLIST"
		#update sourcelist
		$APPDIR/func -playlist_collapse "$ACTIVE_PLAYLIST"
		$APPDIR/func -playlist_expand "$ACTIVE_PLAYLIST"
		echo true > $WORKDIR/UPDATE_SOURCELIST
	fi
	;;

search_track)
	IFS='|' read COMMAND ARTIST TITLE TMP <<< "$(grep -Fm1 "$(<$WORKDIR/SOURCE_PRESS_EVENT)|" $WORKDIR/sourcelist)"
	$APPDIR/func -search_sources "${ARTIST#*\ \ \ \ } $TITLE"
	echo "${ARTIST#*\ \ \ \ } $TITLE" > $WORKDIR/filebrowser_dir
	;;

add_favorites)
	gettext 'Add to Favorites' > $WORKDIR/splashtext
	$APPDIR/box_splash &
	while read I; do
		[ ! "$I" ] && continue
		read TMP < $WORKDIR/tmp_favorite_list
		[ "$TMP" ] && LIST="${TMP}.pmd"
		I=${I#[0-9]*:}
		$APPDIR/func_favorites -add_favorites "$I" "$LIST"
	done < $WORKDIR/SOURCE_PRESS_EVENT
	#---
	sleep 0.5 #splash is for info here
	echo 100 > $WORKDIR/splash
	;;

group_favorites)
	gettext 'Move favorite list to group' > $WORKDIR/splashtext
	$APPDIR/box_splash &
	while read I; do
		[ ! "$I" ] && continue
		I=${I##*/}
		read GROUP < $WORKDIR/tmp_favorite_group
		if [ ! "$GROUP" ]; then
			sleep 0.5 #to get rid of initial splash
			echo 100 > $WORKDIR/splash
			TXT1="$(gettext 'No group is defined')"
			. $APPDIR/box_ok
			exit
		fi
		if [ ! -d "$STORAGE_DIR/favorite_lists/$GROUP" ]; then
			mkdir "$STORAGE_DIR/favorite_lists/$GROUP"
			#add group to sourcelist
			tac $WORKDIR/sourcelist | head -n-1 | tac > $WORKDIR/tmp_sourcelist
			echo "pmusic_favorite_lists|__ $(gettext 'F A V O R I T E   L I S T S') __" > $WORKDIR/sourcelist
			echo "$STORAGE_DIR/favorite_lists/$GROUP|$GROUP||||||||||||$STORAGE_DIR/favorite_lists/$GROUP|gtk-favorites_group" >> $WORKDIR/sourcelist
			cat $WORKDIR/tmp_sourcelist >> $WORKDIR/sourcelist
		fi
		mv "$STORAGE_DIR/favorite_lists/$I" "$STORAGE_DIR/favorite_lists/$GROUP/$I"
		grep -v "$STORAGE_DIR/favorite_lists/$I" $WORKDIR/sourcelist > $WORKDIR/tmp_sourcelist
		mv -f $WORKDIR/tmp_sourcelist $WORKDIR/sourcelist
		echo true > $WORKDIR/UPDATE_SOURCELIST
	done < $WORKDIR/SOURCE_PRESS_EVENT
	#---
	sleep 0.5
	echo 100 > $WORKDIR/splash
	;;

favorites_remove)
	while read I; do
		[ ! "$I" ] && continue
		if [[ "$I" = *.pmd ]]; then
			FILE=${I//pmusicbrowse_*:/}
			FRAME="$(gettext 'Delete')"; IMG="delete"; 
			TXT1="<b>`gettext 'Do you really want to delete the complete Favorite list'`</b>"
			TXT2="$FILE"
			. $APPDIR/box_yesno
			if [ $EXIT = "yes" ]; then
				#we need to check if list is expanded, and if yes, also remove its tracks from sourcelist
				grep -FB 10000 "$FILE" $WORKDIR/sourcelist | grep -v "$FILE" > $WORKDIR/tmp_favorites1
				if [[ "$(<$WORKDIR/sourcelist)" = *"pmusicbrowse_collapse:$FILE"* ]]; then #list is expanded
					grep -FA 10000 "$FILE" $WORKDIR/sourcelist | grep -FA 10000 'pmusic_expand_end|' | tac | head -n-1 | tac > $WORKDIR/tmp_favorites2
				else #list is NOT expanded
					grep -FA 10000 "$FILE" $WORKDIR/sourcelist | grep -v "$FILE" > $WORKDIR/tmp_favorites2
				fi
				cat $WORKDIR/tmp_favorites1 $WORKDIR/tmp_favorites2 > $WORKDIR/sourcelist
				#---
				rm "$FILE"
			fi
		elif [ -d "$I" ] && [[ "$I" = *favorite_lists* ]]; then
			GROUP="$I"
			FRAME="$(gettext 'Delete')"; IMG="delete"; 
			TXT1="<b>`gettext 'Do you really want to delete the complete Favorite group'`</b>"
			TXT2="$GROUP"
			. $APPDIR/box_yesno
			if [ $EXIT = "yes" ]; then
				grep -FB 10000 "${GROUP}|" $WORKDIR/sourcelist | grep -v "${GROUP}|" > $WORKDIR/tmp_favorites1
				grep -FA 10000 "${GROUP}|" $WORKDIR/sourcelist | grep -v "${GROUP}|" > $WORKDIR/tmp_favorites2
				cat $WORKDIR/tmp_favorites1 $WORKDIR/tmp_favorites2 > $WORKDIR/sourcelist
				#---
				rm "$GROUP"/*
				rmdir "$GROUP"
			fi
		elif [ "$FAV_LIST" ]; then #inside favorite list
			#remove from sourcelist - we grep both unique source-id and source-path
			grep -vF "$I" $WORKDIR/sourcelist > $WORKDIR/tmp_favorites
			mv -f $WORKDIR/tmp_favorites $WORKDIR/sourcelist
			#---
			I=${I#[0-9]*:} #remove unique source-nr 
			grep -vF "$I" "$FAV_LIST" > $WORKDIR/tmp_favorites
			mv -f $WORKDIR/tmp_favorites "$FAV_LIST"
		else #a favorite mark
			#remove from sourcelist - we grep both unique source-id and source-path
			grep -vF "$I" $WORKDIR/sourcelist > $WORKDIR/tmp_favorites
			mv -f $WORKDIR/tmp_favorites $WORKDIR/sourcelist
			#---
			I=${I#[0-9]*:}
			grep -vF "$I" "$STORAGE_DIR/favorites" > $WORKDIR/tmp_favorites
			mv -f $WORKDIR/tmp_favorites "$STORAGE_DIR/favorites"
		fi
	done < $WORKDIR/SOURCE_PRESS_EVENT
	echo true > $WORKDIR/UPDATE_SOURCELIST
	;;

favorites_ungroup)
	echo -n > $WORKDIR/tmp_favorites
	tac $WORKDIR/sourcelist | head -n-1 | tac > $WORKDIR/tmp_favorites1 #see updating of sourcelist
	while read I; do
		#update sourcelist
		ls -1 "$I" | awk -F '\n' '{print "pmusicbrowse_expand:$STORAGE_DIR/favorite_lists/" $1 "|" $1 "||||||||||||$STORAGE_DIR/favorite_lists/" $1 "|gtk-audio_playlist_favorites" }' >> $WORKDIR/tmp_favorites
		grep -vF "$I|" $WORKDIR/tmp_favorites1 > $WORKDIR/tmp_favorites2
		mv $WORKDIR/tmp_favorites2 $WORKDIR/tmp_favorites1
		#---
		mv "$I"/* "$STORAGE_DIR/favorite_lists/"
		rmdir "$I"
	done < $WORKDIR/SOURCE_PRESS_EVENT
	#update sourcelist
	echo "pmusic_favorite_lists|__ $(gettext 'F A V O R I T E   L I S T S') __" > $WORKDIR/sourcelist
	cat $WORKDIR/tmp_favorites >> $WORKDIR/sourcelist
	cat $WORKDIR/tmp_favorites1 >> $WORKDIR/sourcelist
	echo true > $WORKDIR/UPDATE_SOURCELIST
	;;

rebuild_album)
	#this code is based on func_trackinfo - refresh album
	#check internet connection
	LANG=C wget --spider --tries 1 -T 3  -F --max-redirect 0 $PING_SERVER 2> $WORKDIR/tmp_rebuild_album
	if [[ "$(<$WORKDIR/tmp_rebuild_album)" != *connected* ]]; then
		TXT1="<b>$(gettext 'Not able to connect to internet')</b>"
		. $APPDIR/box_ok
		exit
	fi
	#---
	TMP=${SOURCE##*/}
	ARTIST=${TMP% - *}
	ALBUM=${TMP#* - }
	ALBUM=${ALBUM%.*}
	#We need disc-ID from DB to retrieve track-list from musicbrainz
	ID_DISC="`grep -F "|${ARTIST}|" "$STORAGE_DIR/index_mymusic" | grep -vE "\.pmu\||\.m3u\||\.pls\|" | grep -F "|${ALBUM}|" | cut -d'|' -f16 | sort | tail -n1`"
	if [ ! "$ID_DISC" ]; then
		TXT1="<b>$(gettext 'Missing album ID')</b>"
		. $APPDIR/box_ok
		exit
	fi
	#progress splash
	gettext 'Rebuilding album.' > $WORKDIR/splashtext
	$APPDIR/box_splash &
	#load artist lines from db only one time. sort by rating
	awk -F'|' '{print $21 "|" $2 "|" $3 "|" $1 }' "$STORAGE_DIR/index_mymusic" | grep -iF "|$ARTIST" | grep -iE "$AUDIO_FORMATS" | sort -n > "$WORKDIR/tmp_fix_$ARTIST"
	#---
	XML="$(wget -q "http://musicbrainz.org/ws/1/release/$ID_DISC?type=xml&inc=tracks+release-events+url-rels" -O- | sed "s/\&amp\;/\&/g;s/\&quot\;/\"/g;s/\&apos;/\'/g;s/\&lt\;/</g;s/\&gt\;/>/g" | tr '>' '\n')"
	TRACKS="`echo "$XML" | tr '>' '\n' | grep -F -A3 '<track id=' | grep -F '</title' | cut -d '<' -f 1`"
	echo "$TRACKS" > $WORKDIR/tmp_rebuild_album
	echo -n > $WORKDIR/tmp_rebuild_album.pmu
	while read TITLE; do
		TITLE=${TITLE%% (*}
		TITLE=${TITLE%%(*}
		ADR="`grep -Fim1 "$TITLE" "$WORKDIR/tmp_fix_$ARTIST" | cut -d'|' -f4`"
		[ ! "$ADR" ] && LENGTH='' || LENGTH="`grep -Fm1 "${ADR}|" "$WORKDIR/tmp_fix_$ARTIST" | cut -d'|' -f12`"
		echo "|$LENGTH|$ARTIST - $TITLE|$ADR|`date +%s%N` $ADR" >> $WORKDIR/tmp_rebuild_album.pmu
	done < $WORKDIR/tmp_rebuild_album
	#save
	if [[ "$(<$WORKDIR/tmp_rebuild_album.pmu)" = *$'\n'* ]]; then
		mv -f $WORKDIR/tmp_rebuild_album.pmu "$STORAGE_DIR/pmu/$ARTIST - ${ALBUM}.pmu"
		#if expanded --> update 
		if [ "`grep -F "pmusicbrowse_collapse:$STORAGE_DIR/pmu/$ARTIST - ${ALBUM}.pmu" $WORKDIR/sourcelist`" ]; then
			$APPDIR/func -playlist_collapse "$STORAGE_DIR/pmu/$ARTIST - ${ALBUM}.pmu"
			$APPDIR/func -playlist_expand "$STORAGE_DIR/pmu/$ARTIST - ${ALBUM}.pmu"
			echo true > $WORKDIR/UPDATE_SOURCELIST
		fi
	fi
	rm $WORKDIR/tmp_fix_*
	echo 100 > $WORKDIR/splash
	;;

fix_album)
	#research non-defined tracks - this code is based on func_trackinfo
	gettext 'Fix album.' > $WORKDIR/splashtext
	$APPDIR/box_splash &
	echo -n > $WORKDIR/tmp_rebuild_album.pmu
	SOURCE=${SOURCE#*:}
	while read I; do
		IFS='|' read COL1 LENGTH NAME ADR ADR_ID <<< "$I"
		if [ -f "$ADR" ]; then
			echo "$I" >> $WORKDIR/tmp_rebuild_album.pmu
			continue
		fi
		A=${NAME% - *}; A=${A%% (*}; A=${A%%(*}; A=${A%% feat*}; A=${A%% ft*}; A=${A%% &*}; ARTIST=${A#The }
		T=${NAME#* - }; T=${T%% (*}; T=${T%%(*}; TITLE=${T#The }
		#load artist lines from db only one time. sort by rating
		[ ! -s "$WORKDIR/tmp_fix_$ARTIST" ] && awk -F'|' '{print length($21) "|" $2 "|" $3 "|" $1 }' "$STORAGE_DIR/index_mymusic" | grep -iF "|$ARTIST" | grep -iE "$AUDIO_FORMATS" | sort -nr > "$WORKDIR/tmp_fix_$ARTIST"
		ADR="`grep -Fim1 "$TITLE" "$WORKDIR/tmp_fix_$ARTIST" | cut -d'|' -f4`"
		[ "$ADR" ] && LENGTH="`grep -Fm1 "${ADR}|" "$STORAGE_DIR/index_mymusic" | cut -d'|' -f12`"
		echo "|$LENGTH|$ARTIST - $TITLE|$ADR|$ADR_ID $ADR" >> $WORKDIR/tmp_rebuild_album.pmu
	done < "${SOURCE}"
	#save
	if 	[[ "$(<$WORKDIR/tmp_rebuild_album.pmu)" = *$'\n'* ]]; then
		mv -f $WORKDIR/tmp_rebuild_album.pmu "$SOURCE"
		#if expanded --> update
		if [[ "$(<$WORKDIR/sourcelist)" = *"pmusicbrowse_collapse:$SOURCE"* ]]; then
			$APPDIR/func -playlist_collapse "$SOURCE"
			$APPDIR/func -playlist_expand "$SOURCE"
			echo true > $WORKDIR/UPDATE_SOURCELIST
		fi
	fi
	rm $WORKDIR/tmp_fix_*
	echo 100 > $WORKDIR/splash
	;;

edit_text)
	export GTK2_RC_FILES="`grep -m1 gtkrc $HOME/.gtkrc-2.0 | cut -d'\"' -f2 2>> $STDERR`" #use global gtk-theme for browser
	$TEXT_EDITOR "${SOURCE#*:}" &
	;;

track_info)
	$APPDIR/func_trackinfo "$SOURCE" -norefresh &
	;;

move_pod)
	$APPDIR/func_podcast -index2mypod "$SOURCE"
	;;

send_to_export)
	if [ "`LC_ALL=C grep -F pmusic <<< "$(LC_ALL=C ps -eo pid,command)" | grep -F func_export`" ]; then #already running --> add to list
		cut -d: -f2- $WORKDIR/SOURCE_PRESS_EVENT >> $WORKDIR/exportlist
	else
		$APPDIR/func_export &
		sleep 0.1
		cut -d: -f2- $WORKDIR/SOURCE_PRESS_EVENT | grep -iE "$AUDIO_FORMATS" > $WORKDIR/exportlist
	fi
	;;

masstagger)
	if [ "`LC_ALL=C grep -F pmusic <<< "$(LC_ALL=C ps -eo pid,command)" | grep -F func_id3tagger`" ]; then #already running --> add to list
		cut -d: -f2- $WORKDIR/SOURCE_PRESS_EVENT >> $WORKDIR/id3tagger
	else
		$APPDIR/func_id3tagger &
		sleep 0.1
		cut -d: -f2- $WORKDIR/SOURCE_PRESS_EVENT | grep -iE "$AUDIO_FORMATS" > $WORKDIR/id3tagger
	fi
	;;

edit_db*)
	echo -n > "$STORAGE_DIR"/index_mymusic.editor
	while read I; do
		[ ! "$(grep -F '/' <<< "$I")" ] && continue
		echo "$(grep -Fm1 "${I}|" "$WORKDIR/sourcelist" | cut -d'|' -f2-4,14-15)" >> "$STORAGE_DIR"/index_mymusic.editor
	done <<< "$SOURCE"
	$APPDIR/func_index -update_index not_empty editor & #not_empty means we ship data 
	;;

rename)
	$APPDIR/func -rename "$SOURCE"
	;;

copy)
	$APPDIR/func -copy "$SOURCE"
	;;

delete)
	$APPDIR/func -delete "$SOURCE"
	;;

show_location)
	$APPDIR/func -show_location "$SOURCE" &
	;;

fix_db)
	$APPDIR/func_add -fix_db &
	;;

edit_marks)
	$TEXT_EDITOR "$STORAGE_DIR"/favorites &
	;;
esac
